package com.shire.shire_interface.controller.friend;

import com.alibaba.fastjson.JSONObject;
import com.shire.shire_interface.common.bin.Response;
import com.shire.shire_interface.common.utils.DateUtil;
import com.shire.shire_interface.constants.Constants;
import com.shire.shire_interface.controller.BaseController;
import com.shire.shire_interface.dao.friend.WxVipUserInfoDao;
import com.shire.shire_interface.model.cs.WxChat;
import com.shire.shire_interface.model.cs.WxChatExample;
import com.shire.shire_interface.model.friend.*;
import com.shire.shire_interface.model.group.WxGroup;
import com.shire.shire_interface.model.group.WxGroupExample;
import com.shire.shire_interface.model.group.WxGroupMember;
import com.shire.shire_interface.model.group.WxGroupMemberExample;
import com.shire.shire_interface.service.chat.WxChatService;
import com.shire.shire_interface.service.friend.VFriendVipInfoService;
import com.shire.shire_interface.service.friend.WxFriendService;
import com.shire.shire_interface.service.group.WxGroupMemberService;
import com.shire.shire_interface.service.group.WxGroupService;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;


//@Api(tags = "加好友 添加好友")
@RestController
@RequestMapping("/friend")
public class WxFriendController extends BaseController {

    @Resource
    private WxFriendService wxFriendService;
    @Resource
    private WxChatService wxChatService;
    @Resource
    private WxGroupService wxGroupService;
    @Resource
    private WxVipUserInfoDao wxVipUserInfoDao;
    @Resource
    private WxGroupMemberService wxGroupMemberService;
    @Resource
    private VFriendVipInfoService vipInfoService;

    @PostMapping(value = "/getVipFriendInfo")
    @ResponseBody
    public Response getVipFriendInfo(@RequestBody JSONObject params ,HttpSession session){
        Response response = new Response();
        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            VFriendVipInfoExample example = new VFriendVipInfoExample();
            VFriendVipInfoExample.Criteria criteria =  example.createCriteria().andWxaccountEqualTo(params.getString("wxAccount"))
                    .andStatusEqualTo(0);

            if (params.containsKey("friendName") && StringUtils.isNotEmpty(params.getString("friendName"))){
                criteria.andFriendnickOrWxidLike(params.getString("friendName"));
            }


            if (params.containsKey("memberState")){
                if("member".equals(params.getString("memberState"))){
                    criteria.andVipEndDateGreaterThan(DateUtil.Date2String(new Date(),"yyyyMMdd"));
                }else if("non-member".equals(params.getString("memberState"))){
                    criteria.andVipEndDateLessThanOrEqualToOrNull(DateUtil.Date2String(new Date(),"yyyyMMdd"));

                }
            }

            addPageParamToExample(params,example);

            Integer count = vipInfoService.selectCountByExample(example);

            if (params.containsKey("sortKey")){
                String sortClause = params.getString("sortKey");
                if (params.containsKey("sortOrder")){
                    sortClause = sortClause + " " + params.getString("sortOrder");
                }
                example.setOrderByClause(sortClause);
            }

            List<VFriendVipInfo> list = vipInfoService.selectByExample(example);

            JSONObject retObj = new JSONObject();
            retObj.put("count", count);
            retObj.put("data",list);

            response.success("成功");
            response.setData(retObj);
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }

//    @ApiOperation(value = "好友列表 csId, wxAccount")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(paramType = "body", dataType = "WxFriend", name = "wxFriend")})
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @PostMapping(value = "/friends")
    @ResponseBody
    public Response allFriends(@RequestBody WxFriend wxFriend, HttpSession session) {
        Response response = new Response();

        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            WxFriendExample friendExample = new WxFriendExample();
            friendExample.createCriteria().andWxaccountEqualTo(wxFriend.getWxaccount()).andIsmycontactEqualTo(1);
            List<WxFriend> allFriends = wxFriendService.getAllFriends(friendExample);
            response.setData(allFriends);
            response.success("成功");
        } catch (Exception e) {
            response.error("失败");
            e.printStackTrace();
        }
        return response;
    }

//    @ApiOperation(value = "有聊天记录的好友列表 csId, wxAccount")
//    @ApiImplicitParams(value = {
//            @ApiImplicitParam(paramType = "body", dataType = "WxChat", name = "wxChat")})
//    @ApiResponses({@ApiResponse(code = 200, message = "调用成功返回", response = Response.class)})
    @PostMapping(value = "/chatFriends")
    @ResponseBody
    public Response chatFriend(@RequestBody WxChat wxChat, HttpSession session) {
        Response response = new Response();
        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }
            WxChatExample example = new WxChatExample();
            WxChatExample.Criteria criteria = example.createCriteria().andWxaccountEqualTo(wxChat.getWxaccount());

            List<WxChat> maxChatIdList = wxChatService.getMaxChatId(example);
            HashMap<Long, Integer> readStatusMap = new HashMap<>();
            List<Long> maxIdList = new ArrayList<>();
            for (WxChat chat : maxChatIdList){
                readStatusMap.put(chat.getId(),chat.getReadstatus());
                maxIdList.add(chat.getId());
            }

            if(maxChatIdList.size() > 0) {
                criteria.andIdIn(maxIdList);
            }
            criteria.andShowstatusEqualTo(Constants.YesNo.YES.getCode());
            example.setOrderByClause("createTime desc");
            example.setLimitStart(0);
            example.setLimitSize(500);
            List<WxChat> wxCharts = wxChatService.chatFriend(example);

            List<String> friendIdList = new ArrayList<>();
            List<String> groupIdList = new ArrayList<>();
            for (WxChat chat : wxCharts){
                if (chat.getFriendwxid().endsWith("@chatroom") && !groupIdList.contains(chat.getFriendwxid())){
                    groupIdList.add(chat.getFriendwxid());
                }else {
                    if (!friendIdList.contains(chat.getFriendwxid())){
                        friendIdList.add(chat.getFriendwxid());
                    }
                }
            }

            Map<String, Object> contactList = new HashMap<>();
            if (friendIdList.size()>0) {
                WxFriendExample friendExample = new WxFriendExample();
                friendExample.createCriteria().andWxaccountEqualTo(wxChat.getWxaccount()).andFriendwxidIn(friendIdList);
                List<WxFriend> wxFriendList = wxFriendService.selectByExample(friendExample);
                for (WxFriend friend : wxFriendList) {
                    contactList.put(friend.getFriendwxid(), friend);
                }
            }

            if (groupIdList.size()>0){
                WxGroupExample groupExample = new WxGroupExample();
                groupExample.createCriteria().andWxaccountEqualTo(wxChat.getWxaccount()).andGroupnoIn(groupIdList);
                List<WxGroup> wxGroupList = wxGroupService.selectByExample(groupExample);
                for (WxGroup group : wxGroupList){
                    contactList.put(group.getGroupno(), group);
                }
            }

            for (WxChat chat : wxCharts){
                if (!contactList.containsKey(chat.getFriendwxid()))
                    continue;

                chat.setNoReadCnt(readStatusMap.get(chat.getId()));
                if (chat.getFriendwxid().endsWith("@chatroom")){
                    WxGroup group = (WxGroup) contactList.get(chat.getFriendwxid());
                    chat.setFriendNick(group.getGroupname());
                    chat.setAvatar(group.getAvatar());
                }else {
                    WxFriend friend = (WxFriend) contactList.get(chat.getFriendwxid());

                    chat.setFriendNick(friend.getFriendnick());
                    chat.setFriendAlias(friend.getFriendalias());
                    chat.setFriendSex(friend.getFriendsex());
                    chat.setFriendSignature(friend.getFriendsignature());
                    chat.setAvatar(friend.getAvatar());
                    chat.setIsTop(friend.getIstop());
                }

            }

            response.success("成功");
            response.setData(wxCharts);
        } catch (Exception e) {
            e.printStackTrace();
            response.error("失败");
        }
        return response;
    }

    @PostMapping(value = "/friendDetail")
    @ResponseBody
    public Response friendDetail(@RequestBody WxFriend wxFriend, HttpSession session) {
        Response response = new Response();
        try {
            if (!checkLoginUser(session)){
                response.error("请登录！");
                response.setCode(501);
                return response;
            }

            JSONObject retData = new JSONObject();

//            WxVipUserInfoExample vipUserInfoExample = new WxVipUserInfoExample();


            VFriendVipInfoExample vipUserInfoExample = new VFriendVipInfoExample();
            vipUserInfoExample.createCriteria().andFriendwxidEqualTo(wxFriend.getFriendwxid()).andWxaccountEqualTo(wxFriend.getWxaccount());

            List<VFriendVipInfo> vipUserInfos = vipInfoService.selectByExample(vipUserInfoExample);
            if (vipUserInfos.size()>0){
                retData.put("vipInfo", vipUserInfos.get(0));
            }


            WxGroupMemberExample memberExample = new WxGroupMemberExample();
            memberExample.createCriteria().andWxaccountEqualTo(wxFriend.getWxaccount()).andWxidEqualTo(wxFriend.getFriendwxid()).andStatusEqualTo(0);
            List<WxGroupMember> members = wxGroupMemberService.selectByExample(memberExample);

            List<String> groupIds = new ArrayList<>();
            for (WxGroupMember mb : members){
                groupIds.add(mb.getGroupno());
            }

            WxGroupExample groupExample = new WxGroupExample();
            groupExample.createCriteria().andWxaccountEqualTo(wxFriend.getWxaccount()).andGroupnoIn(groupIds);
            List<WxGroup> groups = wxGroupService.getAllGroups(groupExample);
            if (groups.size()>0){
                retData.put("groups", groups);
            }

            response.success("成功");
            response.setData(retData);
        } catch (Exception e) {
            e.printStackTrace();
            response.error("失败");
        }
        return response;
    }
}
